package com.ikun.hosuserservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ikun.common.entity.ResponseResult;
import com.ikun.common.entity.ResponseStatus;
import com.ikun.common.entity.User;
import com.ikun.hosuserservice.entity.UserData;
import com.ikun.hosuserservice.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.swing.*;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * 注册
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @PostMapping("/register")
    public ResponseResult register(@RequestBody UserData u) {
        /*判断该用户是否存在*/
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", u.getPhone());
        boolean b = userService.count(queryWrapper) > 0;
         if (b) {
            return ResponseResult.error(ResponseStatus.BUSINESS_ERROR, "该用户已存在");
        } else {
            User user = new User(u.getUsername(), u.getNickname(), u.getPhone(), u.getPassword(), LocalDateTime.now(), 0);
            user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
            user.setCreateTime(new Date());
            userService.save(user);
            return ResponseResult.ok("注册成功");
        }
    }

}
